<?php
//$Id$

class MobileApp extends App{

    function __construct(){
        parent::__construct();
    }

    private function initCity($city){
        $cityArray  = Core::getConfig('city.array');
        $cityIndex  = Core::getConfig('city.index');
        $defaultId  = Core::getConfig('default.cityid');

        if(isset($cityIndex[$city])){
            $this->cityInfo = $cityArray[$cityIndex[$city]];
            Core::setCookie('SudingkeCityId', $this->cityInfo[0], 60, '/', '.sudingke.net');
        }else{
            $defaultCityInfo = Core::getDefaultCityInfo();

            header('Location: http://m.sudingke.net/'.$defaultCityInfo[2].'/');
            exit();
        }
    }

    /*
        根据Url结构唯一确定一个应用模型
        功能：通过路由，解析出 CityId, Action，Method，Params

        // http://m.sudingke.net/{$city}/api/<$version>/{$action}/{$method}
        // http://m.sudingke.net/{$city}/{$action}/{$method}/{$params}

    */
    function run(){
        $perfix = substr($_SERVER['HTTP_HOST'], 0, -13); // strlen('.sudingke.com')
        if($perfix == 'm'){
            $cityArray  = Core::getConfig('city.array');
            $cityIndex  = Core::getConfig('city.index');
            $defaultId  = Core::getConfig('default.cityid');

            @list(, $city, $action, $tmp3, $tmp4) = explode('/', $_SERVER['REDIRECT_URL'], 5);

            $this->initCity($city);

            if($action == 'api'){
                $version = $tmp3;
                @list($method, $format) = explode('.', $tmp4);
                if($format != 'json') $format = 'xml';

                $this->runApi($version, $format, $method);
            }else{
                $method = $tmp3;
                $params = $tmp4;
                $this->runAct($action, $method, $params);
            }
p($this);
        }else{
            header('Location: http://m.sudingke.net');
            exit();
        }
    }

    function runApi($version, $format, $method){
        $ver = str_replace('.', '_', $version);

        Core::import("apps.mobile.api.ISudingkeAPI");
        Core::import("apps.mobile.api.{$ver}.SudingkeAPI");
        if(class_exists('SudingkeAPI')){
            $this->action = new SudingkeAPI($version, $format);
            $this->action->setMethod($method);
            $this->action->process();
        }else{
            self::retArray(array('scuess' => false, 'message' => 'Invalid API'), $format);
        }
    }

    function runAct($action, $method, $params){
        $this->runAction($action, $method, $params);
    }

    public static function retArray(array $arr, $format = 'json'){
        if($format == 'xml'){
            p($arr);
        }else{ //json
            echo json_encode($arr);
        }
    }
}
?>